package org.goodsl.mdd;

import groovy.lang.Closure;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 13-1-16
 * Time: 下午3:33
 * Copyright goodsl.org 2012~2020
 */
public class DependExecuteDelegate {
    public Box thisBox;

    private HashMap<String,Closure> subCalculators;

    DependExecuteDelegate(Box box) {
        thisBox = box;
    }

    public Object methodMissing(String boxSegName, Object args) {
        List argsList = (List)args;
        if(subCalculators == null)
            subCalculators = new HashMap<String,Closure>(3);

        Closure calc = subCalculators.get(boxSegName);
        if(calc == null){
            if (args != null && argsList.size() > 0 && argsList.get(0) instanceof Closure) {
                Closure cl = (Closure)argsList.get(0);
                DependExecuteDelegate newDelegate = new DependExecuteDelegate(thisBox);
                calc = cl.rehydrate(newDelegate,thisBox,thisBox);
                calc.setResolveStrategy(Closure.DELEGATE_FIRST);
                subCalculators.put(boxSegName,calc);

            }
        }

        if(calc!=null){
            Object boxSegInstance = thisBox.getSeg(boxSegName);
            //将字段本身作为闭包的默认参数.递归执行，这里是解析时间的执行，主要用于计算依赖关系
            Object newValue = calc.call(boxSegInstance);
            return newValue;
        }
        return null;

    }
}
